package com.nhjf.mobile.controller.followThePainting;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.nhjf.command.followThePainting.FollowThePaintingCommand;
import com.nhjf.common.page.Pagination;
import com.nhjf.mobile.common.util.ImageTools;
import com.nhjf.mobile.common.util.SysProperties;
import com.nhjf.model.followThePainting.FollowThePainting;
import com.nhjf.model.followThePainting.followThePaintingDetails.FollowThePaintingDetails;
import com.nhjf.model.system.AdminSession;
import com.nhjf.model.system.Role;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.Courses;
import com.nhjf.pojo.dto.followThePainting.followThePaintingDto;
import com.nhjf.pojo.dto.result.ServiceResultDto;
import com.nhjf.pojo.qo.followThePainting.FollowThePaintingCommentQo;
import com.nhjf.pojo.qo.followThePainting.FollowThePaintingQo;
import com.nhjf.pojo.qo.followThePainting.followThePaintingDetailsQo.FollowThePaintingDetailsQo;
import com.nhjf.pojo.qo.system.AdminSessionQo;
import com.nhjf.pojo.qo.system.UserQo;
import com.nhjf.service.followThePainting.FollowThePaintingCommentService;
import com.nhjf.service.followThePainting.FollowThePaintingService;
import com.nhjf.service.followThePainting.followThePaintingDetails.FollowThePaintingDetailsService;
import com.nhjf.service.system.AdminSessionService;
import com.nhjf.service.system.UserService;

import net.sf.json.JSONObject;

@RequestMapping("/ftp")
@Controller
public class FollowThePaintingController {
	@Autowired
	private FollowThePaintingService followThePaintingService;
	@Autowired
	private FollowThePaintingDetailsService paintingDetailsService;
	@Autowired
	private FollowThePaintingCommentService followThePaintingCommentService;
	@Autowired
	private AdminSessionService adminSessionService;
	@Autowired
	private UserService userService;

	//跟着画列表
	@ResponseBody
	@RequestMapping("/followThePainting_list")
	public String followThePainting(@RequestParam(value = "page", defaultValue = "1")Integer page,String typeOne,String typeTwo) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		Pagination pagination = new Pagination();
		pagination.setPageSize(10);
		pagination.setPageNo(page);
		try {
			FollowThePaintingQo followThePaintingQo=new FollowThePaintingQo();
			if(StringUtils.isNotEmpty(typeOne)){
				followThePaintingQo.setTypeOne(Long.parseLong(typeOne));
			}
			if(StringUtils.isNotEmpty(typeTwo)){
				followThePaintingQo.setTypeTwo(Long.parseLong(typeTwo));
			}
			pagination.setCondition(followThePaintingQo);
			pagination = followThePaintingService.queryPagination(pagination);
			List<FollowThePainting> followThePaintingList=(List<FollowThePainting>)pagination.getList();
			SysProperties sysProperties=SysProperties.getInstance();
			String imagePath=sysProperties.get("imagePath");
			for(FollowThePainting followThePainting:followThePaintingList) {

				if(StringUtils.isNotEmpty(followThePainting.getCover())) {
					followThePainting.setCover(imagePath+"/followThePainting/"+followThePainting.getCover());

				}

			}
			resMap.put("code", "200");
			resMap.put("message", pagination);
			return JSONObject.fromObject(resMap).toString();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "系统异常");
			return JSONObject.fromObject(resMap).toString();
		}
	}
	//跟着画详情
	@ResponseBody
	@RequestMapping("/followThePainting_details")
	public String followThePaintingDetails(@RequestParam(value="followThePaintingId", required=true)String  followThePaintingId) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		FollowThePaintingDetailsQo qo=new FollowThePaintingDetailsQo();
		qo.setFollowThePaintingId(Long.parseLong(followThePaintingId));
		List<FollowThePaintingDetails> followThePaintingList=paintingDetailsService.queryList(qo);
		SysProperties sysProperties=SysProperties.getInstance();
		String imagePath=sysProperties.get("imagePath");
		for(FollowThePaintingDetails details:followThePaintingList){
			details.setDetailPicture(imagePath+"/followThePainting/"+details.getDetailPicture());
		}
		FollowThePaintingQo followThePaintingQo=new FollowThePaintingQo();
		followThePaintingQo.setFollowThePaintingId(Long.parseLong(followThePaintingId));
		followThePaintingQo.setSeachTypeOne(true);
		followThePaintingQo.setSeachTeacher(true);
//		followThePaintingQo.setSeachFollowThePaintingDetails(true);
		followThePaintingQo.setSeachTypeTwo(true);
		FollowThePainting followThePainting= followThePaintingService.queryUnique(followThePaintingQo);
		if(followThePainting!=null) {
			followThePainting.setPopularity((followThePainting.getPopularity()==null?0:followThePainting.getPopularity())+1);
			followThePaintingService.update(followThePainting);
		}
		followThePaintingDto dto=new followThePaintingDto();
		dto.setFollowThePaintingDetailsList(followThePaintingList);
		dto.setFtsTitle(followThePaintingService.get(Long.parseLong(followThePaintingId)).getFtsTitle());
		FollowThePaintingCommentQo followThePaintingCommentQo=new FollowThePaintingCommentQo();

		followThePaintingCommentQo.setFollowThePaintingId(Long.parseLong(followThePaintingId));
		int num=followThePaintingCommentService.queryCount(followThePaintingCommentQo);
		dto.setCommentNum(num);
		resMap.put("code", "200");
		resMap.put("message", dto);
		return JSONObject.fromObject(resMap).toString();
	}
	@ResponseBody
	@RequestMapping("/followThePainting_save")
	public String followThePaintingSave(@RequestParam("files") MultipartFile[] files,@RequestParam("imag")MultipartFile imag,HttpServletRequest request,HttpServletResponse response,FollowThePaintingCommand command) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		String ids="11";
		try {
			if(files.length<1) {
				resMap.put("code", "500");
				resMap.put("message", "请选择要上传的图片！");
				return JSONObject.fromObject(resMap).toString();
			}
			List<String> strlist=new ArrayList<String>();
			String dateString= new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
			for (int i=1 ;i<=files.length;i++ ) {
				int returnTag = -1;
				SysProperties sysProperties=SysProperties.getInstance();

				String followThePicture=sysProperties.get("followThePicture");
				//获取图片原始文件名
				String finetTalk = files[i-1].getOriginalFilename();
				System.out.println(finetTalk);
				//文件名使用当前时间
				String name = dateString+"-"+i;
				// 获取上传图片的扩展名(jpg/png/...)
				String extension = FilenameUtils.getExtension(finetTalk);
				String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
				boolean flag = false;
				// 判断文件格式是否合法
				for (String str : regular) {
					if (extension.equalsIgnoreCase(str)) {
						flag = true;
					}
				}
				if (!flag) {
					returnTag = 0;
					resMap.put("code", "500");
					resMap.put("message", "上传图片格式不正确！");
					return JSONObject.fromObject(resMap).toString();
				}
				// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
				String path =followThePicture+"/"+ids +"/" +name + "." + extension;
				strlist.add(ids +"/" +name + "." + extension);
				//图片上传的绝对路径

				File dir = new File(path);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				// 上传图片
				files[i-1].transferTo(new File(path));
				command.setImgList(strlist);
			}
			if (imag.isEmpty()) {
				resMap.put("code", "500");
				resMap.put("message", "上传图片不可为空");
				return JSONObject.fromObject(resMap).toString();
			}
			int returnTag = -1;
			SysProperties sysProperties=SysProperties.getInstance();
			String followThePicture=sysProperties.get("followThePicture");
			//获取图片原始文件名
			String finetTalk = imag.getOriginalFilename();
			System.out.println(finetTalk);
			//文件名使用当前时间
			String name = dateString+"-1";
			// 获取上传图片的扩展名(jpg/png/...)
			String extension = FilenameUtils.getExtension(finetTalk);
			String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
			boolean flag = false;
			// 判断文件格式是否合法
			for (String str : regular) {
				if (extension.equalsIgnoreCase(str)) {
					flag = true;
				}
			}
			if (!flag) {
				returnTag = 0;
				resMap.put("code", "500");
				resMap.put("message", "上传图片格式不正确！");
				return JSONObject.fromObject(resMap).toString();
			}
			// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）

			String path =followThePicture+ids +"/" +name + "." + extension;
			//图片上传的绝对路径

			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 上传图片
			imag.transferTo(new File(path));
			int width=ImageTools.getImgWidth(dir);
			int height=ImageTools.getImgHeight(dir);
			command.setWidth(width);
			command.setHeight(height);
			command.setCover(ids+"/" +name + "." + extension);
			ServiceResultDto dto=followThePaintingService.createFollowThePaintingComment(command);
			if(dto.getSuccess()) {
				resMap.put("code", "200");
				resMap.put("message", "上传成功");
				return JSONObject.fromObject(resMap).toString();
			}else {
				return "500";
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resMap.put("code", "500");
		resMap.put("message", "系统异常");
		return JSONObject.fromObject(resMap).toString();
	}
}
